package top.zsyle.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginCheckFilter extends ZuulFilter {

    /**
     * 通过返回的字符串指定过滤器类型
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器执行时机，数字越小越优先执行
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 判断要不要执行run方法
     * @return
     */
    @Override
    public boolean shouldFilter() {
        // url是请求的全路径，包括ip+port...  uri是只有路径
        // 1.判断是否访问的是公共路径
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String uri = request.getRequestURI();
        // 2.当请求路径是登陆或者是注册那么就不执行登陆校验
        if (uri.endsWith("login") || uri.endsWith("register")){
            return false;
        }
        // 3.如果访问的不是公共路径，那么就要执行登陆校验
        return true;
    }

    /**
     * 执行当前过滤器的核心业务方法
     * @return
     * @throws ZuulException
     */
    @SneakyThrows
    @Override
    public Object run() throws ZuulException {
        // 1.获取到请求头中的token
        RequestContext context = RequestContext.getCurrentContext();
        String token = context.getRequest().getHeader("token");
        // 2.判断是否登陆
        if (StringUtils.isEmpty(token)){
            // 3.没有登陆
            HttpServletResponse response = context.getResponse();
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            Map<String, Object> map = new HashMap<>();
            map.put("message", "请登录！");
            map.put("success", false);
            map.put("obj", "noLogin");
            // 利用阿里的fastjson，将map对象转换为json字符串
            String jsonStr = JSON.toJSONString(map);
            writer.write(jsonStr);
            // 让当前请求跳过路由，直接走后置响应给浏览器
            RequestContext.getCurrentContext().setSendZuulResponse(false);
            writer.close();
        }
        return true;
    }
}
